<template>
  <el-row class="tac">
    <!-- 左侧导航栏 -->
    <el-col :span="6">
      <h5>导航</h5>
      <el-menu :default-active="activeMenu" class="el-menu-vertical-demo" @select="handleMenuSelect">
        <el-menu-item index="shopping">
          <i class="el-icon-menu"></i>
          <span>购物</span>
        </el-menu-item>
        <el-menu-item index="infoQuery">
          <i class="el-icon-menu"></i>
          <span>订单查询</span>
        </el-menu-item>
      </el-menu>
    </el-col>

    <!-- 右侧内容区域 -->
    <el-col :span="18" class="content-area">
      <!-- 商家列表 -->
      <div v-if="activeMenu === 'shopping' && !selectedStore">
        <h3>商家列表</h3>
        <div v-for="(store, index) in stores" :key="index" class="store-card">
          <el-card shadow="always">
            <div slot="header" class="clearfix">
              <span>{{ store.username }}</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="enterStore(store)">进入店铺</el-button>
            </div>
            <div class="store-details">
              <el-rate v-model="store.rating" disabled show-score text-color="#ff9900" score-template="{value}分"></el-rate>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 商品列表 & 订单详情 -->
      <div v-if="selectedStore">
        <el-page-header @back="goBack" :content="`${selectedStore.username} - 商品列表`"></el-page-header>

        <div v-for="(product, index) in selectedStore.products" :key="index" class="product-card">
          <el-card shadow="always">
            <div slot="header" class="clearfix">
              <span class="product-name">{{ product.productName }}</span>
              <span class="product-price">¥{{ product.price }}</span>
            </div>
            <div class="product-details">
              <div class="quantity-control">
                <el-button @click="decreaseQuantity(product)" :disabled="product.quantity <= 0">-</el-button>
                <span class="quantity">{{ product.quantity }}</span>
                <el-button @click="increaseQuantity(product)">+</el-button>
              </div>
            </div>
          </el-card>
        </div>

        <div class="total-price">
          <h3>总价: ¥{{ totalPrice }}</h3>
        </div>

        <el-button type="primary" @click="showOrderDialog" :disabled="totalPrice <= 0">提交订单</el-button>
      </div>

      <!-- 订单确认弹窗 -->
      <el-dialog title="订单确认" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
        <div class="order-dialog-content">
          <div class="address-section">
            <h4>收货信息</h4>
            <el-form :model="orderForm" :rules="rules" ref="orderForm" label-width="100px">
              <el-form-item label="收货人" prop="name">
                <el-input v-model="orderForm.name" placeholder="请输入收货人姓名"></el-input>
              </el-form-item>
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="orderForm.phone" placeholder="请输入联系电话"></el-input>
              </el-form-item>
              <el-form-item label="收货地址" prop="address">
                <el-input type="textarea" v-model="orderForm.address" placeholder="请输入详细收货地址" :rows="3"></el-input>
              </el-form-item>
            </el-form>
          </div>

          <div class="order-details">
            <h4>订单详情</h4>
            <el-table :data="orderProducts" style="width: 100%">
              <el-table-column prop="productName" label="商品名称" width="180"></el-table-column>
              <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
              <el-table-column prop="price" label="单价">
                <template slot-scope="scope">¥{{ scope.row.price }}</template>
              </el-table-column>
              <el-table-column prop="subtotal" label="小计">
                <template slot-scope="scope">¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}</template>
              </el-table-column>
            </el-table>

            <div class="order-total">
              <h3>订单总价: ¥{{ totalPrice }}</h3>
            </div>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitOrder">确认下单</el-button>
        </span>
      </el-dialog>

       <!-- 订单查询界面 -->
       <div v-if="activeMenu === 'infoQuery'">
        <h3>我的订单列表</h3>
        <div v-for="order in mergedOrders" :key="order.id" class="order-card">
          <el-card shadow="hover" class="order-detail-card">
            <h4>消费者信息</h4>
            <p>交易商家: {{ order.storeName }}</p>
            <p>订单详情: {{ order.products }}</p>
            <p>订单地址: {{ order.deliveryAddress }}</p>
            <p>下单时间: {{ order.orderTime }}</p>
            <p>区块链交易ID: {{ order.consumerTransactionId }}</p>

            <h4>商家信息</h4>
            <p>接单时间: {{ order.merchantInfo?.acceptTime || ' ' }}</p>
            <p>订单完成时间: {{ order.merchantInfo?.completionTime || ' ' }}</p>
            <p>区块链交易ID: {{ order.merchantInfo?.merchantTransactionId || ' ' }}</p>

            <h4>配送员信息</h4>
            <p>配送员名: {{ order.deliveryInfo?.deliveryPersonName || ' ' }}</p>
            <p>接单时间: {{ order.deliveryInfo?.acceptTime || ' ' }}</p>
            <p>订单完成时间: {{ order.deliveryInfo?.completionTime || ' ' }}</p>
            <p>区块链交易ID: {{ order.deliveryInfo?.deliveryTransactionId || ' ' }}</p>
          </el-card>
        </div>
        <div v-if="mergedOrders.length === 0" class="no-order">
          <el-empty description="暂无订单信息"></el-empty>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      userId: null,
      activeMenu: "shopping",
      stores: [], // 商家列表
      selectedStore: null, // 当前选中的商家
      dialogVisible: false, // 订单弹窗状态
      orderForm: {
        name: "",
        phone: "",
        address: "",
      },
      consumerOrders: [], // 添加消费者订单数组初始化
      merchantDeliveryOrders: [], // 商家和配送订单
      rules: {
        name: [{ required: true, message: "请输入收货人姓名", trigger: "blur" }],
        phone: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
        address: [{ required: true, message: "请输入收货地址", trigger: "blur" }]
      }
    };
  },
  created() {
    this.userId = this.$route.query.id;
    if (!this.userId) {
      console.error("用户 ID 不存在，无法加载页面数据！");
      this.$message.error('缺少用户信息，无法加载数据！');
      return;
    }
    this.fetchStores();
    this.fetchAllOrders();
  },
  computed: {
    totalPrice() {
  // 确保 selectedStore 和 products 都是有效值
      if (!this.selectedStore || !Array.isArray(this.selectedStore.products)) {
        return 0;
      }

      // 安全调用 reduce
      return this.selectedStore.products.reduce((total, p) => total + p.price * p.quantity, 0).toFixed(2);
},
    orderProducts() {
      // 确保 selectedStore 和 products 存在且为数组
      if (!this.selectedStore || !Array.isArray(this.selectedStore.products)) {
        return [];
      }

      // 安全调用 filter 方法
      return this.selectedStore.products.filter((p) => p.quantity > 0);
    },
        // 合并订单数据
        mergedOrders() {
        const mergedMap = new Map();
        
        // 处理消费者订单
        this.consumerOrders.forEach(order => {
          mergedMap.set(order.code, {
            ...order,
            merchantInfo: {},
            deliveryInfo: {}
          });
        });

        // 合并商家和配送订单信息
        this.merchantDeliveryOrders.forEach(order => {
          if (mergedMap.has(order.code)) {
            const existingOrder = mergedMap.get(order.code);
            const updatedOrder = {
              ...existingOrder,
              merchantInfo: {
                ...existingOrder.merchantInfo,
                ...order.merchantInfo
              },
              deliveryInfo: {
                ...existingOrder.deliveryInfo,
                ...order.deliveryInfo
              }
            };
            mergedMap.set(order.code, updatedOrder);
          }
        });

        return Array.from(mergedMap.values()).sort((a, b) => 
          new Date(b.orderTime) - new Date(a.orderTime)
        );
      }
    },
  methods: {
    async fetchStores() {
      try {
        const response = await this.$axios.get('/getStores');
        if (response.data) {
          if (response.data.code === "200") {
            this.$message.success('查询成功！');
            this.stores = response.data.o;
          } else {
            this.$message.error(response.data.message || '查询商家列表失败');
          }
        }
      } catch (error) {
        console.error("获取商家列表失败:", error);
        this.$message.error('服务器错误，无法获取商家列表');
      }
    },
    async fetchGoods(storeId) {
      try {
        const response = await this.$axios.get('/getgoods', {
          params: { userid: storeId }
        });
        if (response.data && response.data.code === "200") {
          this.$message.success('商品列表获取成功！');
          return response.data.o.map(product => ({
            ...product,
            quantity: 0 // 初始化每个商品的数量
          }));
        } else {
          this.$message.error(response.data.message || '获取商品列表失败');
          return [];
        }
      } catch (error) {
        console.error("获取商品列表失败:", error);
        this.$message.error('服务器错误，无法获取商品列表');
        return [];
      }
    },
    async fetchAllOrders() {
      try {
        // 先执行 fetchConsumerOrders
        await this.fetchConsumerOrders();

        // 然后执行 fetchMerandDelOrders，确保 consumerOrders 已经加载完毕
        await this.fetchMerandDelOrders();
      } catch (error) {
        console.error("获取订单信息失败:", error);
        this.$message.error('获取订单信息失败');
      }
},
    async fetchConsumerOrders() {
      try {
        const response = await this.$axios.get('/getConsumerorder', {
          params: { userid: this.userId }
        });

        if (response.data && response.data.code === "200") {
          this.consumerOrders = this.processOrders(response.data.o);
          if (this.consumerOrders.length === 0) {
            console.warn('消费者订单为空');
          }
        } else {
          throw new Error(response.data.message || '获取消费者订单失败');
        }
      } catch (error) {
        console.error("获取消费者订单失败:", error);
        this.consumerOrders = [];
        this.$message.error( response.data.msg||'服务器错误，无法获取消费者订单');
      }
},
        async fetchMerandDelOrders() {
          try {
            // 获取所有消费者订单的 code
            const codes = this.consumerOrders.map(order => order.code);
            this.merchantDeliveryOrders = [];

            for (const code of codes) {
              if (!code) continue;

              // 请求获取商家和配送订单
              const response = await this.$axios.get('/getMerandDelOrders', {
                params: { code }
              });

              if (response.data && response.data.code === "200") {
                const processedOrders = response.data.o
                  .map(order => {
                    let content = {};
                    try {
                      // 尝试解析 content 字段，兼容字符串和对象
                      content = typeof order.content === 'string' 
                        ? JSON.parse(order.content) 
                        : (order.content || {});
                    } catch (e) {
                      console.error('解析订单内容失败:', order, e);
                      content = {};
                    }

            // 根据内容创建商家和配送信息
            return {
              code: order.code,
              merchantInfo: content.merchantAcceptTime || content.merchantCompleteTime 
                ? {
                    acceptTime: content.merchantAcceptTime || '',
                    completionTime: content.merchantCompleteTime || '',
                    merchantTransactionId: order.hashNo || ''
                  }
                : {},
              deliveryInfo: content.riderCompleteTime || content.riderAcceptTime || content.deliveryname
                ? {
                    deliveryPersonName: content.deliveryname || '',
                    acceptTime: content.riderAcceptTime || '',
                    completionTime: content.riderCompleteTime || '',
                    deliveryTransactionId: order.hashNo || ''
                  }
                : {}
            };
          })
          .filter(order => 
            Object.keys(order.merchantInfo).length > 0 || 
            Object.keys(order.deliveryInfo).length > 0
          );

        this.merchantDeliveryOrders.push(...processedOrders);
      }
    }
  } catch (error) {
    console.error("获取商家和配送订单失败:", error);
    this.$message.error('服务器错误，无法获取商家和配送订单');
  }
},
// 修改订单数据处理方法
    processOrders(orders) {
      if (!Array.isArray(orders)) {
        console.warn('processOrders received invalid input:', orders);
        return [];
      }

      return orders.map(order => {
        let contentObj = {};
        try {
          // 兼容多种数据类型
          contentObj = typeof order.content === 'string' 
            ? JSON.parse(order.content) 
            : (order.content || {});
        } catch (e) {
          console.error('解析 content 失败:', e);
          contentObj = order.content || {};
        }

        // 更加灵活的字段映射
        return {
          id: order.id,
          code: order.code,
          storeName: contentObj.storeName || '',
          products: this.formatProducts(contentObj.products),
          deliveryAddress: contentObj.deliveryAddress || '',
          orderTime: contentObj.orderTime || contentObj.orderTime || order.createTime || '',
          consumerTransactionId: order.hashNo || '',
          merchantInfo: {
            acceptTime: contentObj.merchantAcceptTime || '',
            completionTime: contentObj.merchantCompleteTime || '',
            merchantTransactionId: order.hashNo || ''
          },
          deliveryInfo: {
            deliveryPersonName: contentObj.deliveryname || contentObj.username || '',
            acceptTime: contentObj.riderAcceptTime || '',
            completionTime: contentObj.riderCompleteTime || '',
            deliveryTransactionId: order.hashNo || ''
          }
        };
      });
    },

    // 新增：格式化商品信息的辅助方法
    formatProducts(products) {
      if (typeof products === 'string') {
        return products;
      }
      if (Array.isArray(products)) {
        return products.map(p => `${p.productName}: ${p.quantity}件`).join(', ');
      }
      return '';
    },
    handleMenuSelect(index) {
      this.activeMenu = index;
      if (index === "infoQuery") {
        this.selectedStore = null;
        this.dialogVisible = false;
      }
    },
    async enterStore(store) {
      // 复制店铺信息并获取商品
      this.selectedStore = { ...store, products: [] }; 
      const products = await this.fetchGoods(store.userid);
      this.selectedStore.products = products;
    },
    goBack() {
      this.selectedStore = null; // 返回商家列表
    },
    showOrderDialog() {
      this.dialogVisible = true; // 显示订单弹窗
    },
    handleClose(done) {
      this.dialogVisible = false; // 关闭订单弹窗
    },
    increaseQuantity(product) {
      product.quantity++; // 增加商品数量
    },
    decreaseQuantity(product) {
      if (product.quantity > 0) product.quantity--; // 减少商品数量
    },

    async submitOrder() {
      this.$refs.orderForm.validate(async (valid) => {
        if (valid) {
          const orderData = {
            userid: this.userId,
            username: this.orderForm.name,
            storeName: this.selectedStore.username,
            products: this.orderProducts.map(p => `${p.productName}: ${p.quantity}件`).join(', '),
            totalprice: this.totalPrice,
            deliveryAddress: this.orderForm.address,
            phoneNum: this.orderForm.phone,
            orderTime: new Date().toLocaleString()
          };
          try {
            const response = await this.$axios.post('/consumerOrder', orderData);
            if (response.data && response.data.code === "200") {
              this.$message.success('下单成功！');

              // 重新获取所有订单数据
              await this.fetchAllOrders();

              // 关闭弹窗并重置表单
              this.dialogVisible = false;
              this.resetForm();
            } else {
              throw new Error(response.data.message || '下单失败');
            }
          } catch (error) {
            console.error("下单失败:", error);
            this.$message.error('服务器错误，无法提交订单');
          }
        } else {
          this.$message.error("请完善订单信息！");
        }
      });
},

resetForm() {
  // 重置表单数据和商品数量
  Object.keys(this.orderForm).forEach((key) => (this.orderForm[key] = ""));
  this.selectedStore.products.forEach((product) => (product.quantity = 0));
}

  }
};
</script>




<style scoped>
.content-area {
  padding: 20px;
  background-color: #f9f9f9;
}
.store-card, .product-card {
  width: 100%;
  margin-top: 20px;
}
.product-details {
  font-size: 16px;
}
.product-name, .product-price {
  font-size: 16px;
  margin-right: 20px;
}
.product-name {
  flex: 1;
  font-weight: bold;
}
.product-price {
  font-weight: bold;
  color: #f56c6c;
}
.product-card .el-card__header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.quantity-control {
  display: flex;
  align-items: center;
}
.quantity {
  margin: 0 10px;
  font-size: 16px;
}
.total-price {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}
.order-dialog-content {
  padding: 20px 0;
}
.address-section {
  margin-bottom: 30px;
}
.order-details {
  margin-top: 20px;
}
.order-total {
  margin-top: 20px;
  text-align: right;
  color: #f56c6c;
}
h4 {
  margin-bottom: 20px;
  font-size: 16px;
  color: #303133;
}

</style>